package lol.clann.bukkit.pluginboot.model;

import lol.clann.bukkit.pluginboot.util.ItemStackUtils;
import lol.clann.clannboot.annotation.inject.Inject;
import lol.clann.clannboot.context.BeanContext;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author pyz
 * @date 2018/8/12 下午3:46
 */
public class ItemStackBuilder {
    private Material material;
    private short duriability = 0;
    private int quantity = 1;

    private String displayName;
    private List<String> lore = new ArrayList<>();
    private Map<Enchantment, Integer> enchantments = new HashMap<>();

    @Inject
    private ItemStackUtils itemStackUtils;

    private ItemStackBuilder() {
        BeanContext.inject(this);
    }

    public static ItemStackBuilder builder() {
        return new ItemStackBuilder();
    }

    public ItemStackBuilder material(Material material) {
        this.material = material;
        return this;
    }

    public ItemStackBuilder duriability(short duriability) {
        this.duriability = duriability;
        return this;
    }

    public ItemStackBuilder displayName(String displayName) {
        this.displayName = displayName;
        return this;
    }

    public ItemStackBuilder lore(List<String> lore) {
        this.lore = lore == null ? new ArrayList<>() : lore;
        return this;
    }

    public ItemStackBuilder enchantment(Enchantment enchantment, int level) {
        enchantments.put(enchantment, level);
        return this;
    }

    public ItemStackBuilder addLore(String lore) {
        this.lore.add(lore);
        return this;
    }

    public ItemStackBuilder quantity(int quantity) {
        this.quantity = quantity;
        return this;
    }

    public ItemStack build() {
        ItemStack itemStack = new ItemStack(material);
        itemStack.setAmount(quantity);
        itemStack.setDurability(duriability);
        itemStack = itemStackUtils.asCraftCopy(itemStack);
        ItemMeta meta = itemStack.getItemMeta();
        if (displayName != null) {
            meta.setDisplayName(displayName);
        }
        if (!lore.isEmpty()) {
            meta.setLore(lore);
        }
        itemStack.setItemMeta(meta);
        for (Map.Entry<Enchantment, Integer> en : enchantments.entrySet()) {
            itemStackUtils.addEnchantment(itemStack, (short) en.getKey().getId(), en.getValue().shortValue());
        }
        return itemStack;
    }

}
